﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CprExam.Model;
using GalaSoft.MvvmLight.Command;
using GLCommon;
using Newtonsoft.Json.Linq;

namespace CprExam.ViewModel
{
    public class ExamingViewModel:VmBase
    {
        private SerialPort _serialPort;
        private bool _canAppend;
        private string _recv;
        private string _message;
        /// <summary>
        /// 提示消息
        /// </summary>
        public string Message
        {
            get { return _message; }
            set { _message = value; RaisePropertyChanged("Message"); }
        }

        private string _buttonText;
        /// <summary>
        /// ButtonText
        /// </summary>
        public string ButtonText
        {
            get { return _buttonText; }
            set { _buttonText = value; RaisePropertyChanged("ButtonText"); }
        }

        private string _scoreText;
        /// <summary>
        /// ScoreText
        /// </summary>
        public string ScoreText
        {
            get { return _scoreText; }
            set { _scoreText = value; RaisePropertyChanged("ScoreText"); }
        }
        private bool _isExaming;
        /// <summary>
        /// 是否考试中
        /// </summary>
        public bool IsExaming
        {
            get { return _isExaming; }
            set { _isExaming = value; RaisePropertyChanged("IsExaming"); }
        }

        private ExamineeInfoApi _examineeInfo;
        /// <summary>
        /// 当前考生信息
        /// </summary>
        public ExamineeInfoApi ExamineeInfo
        {
            get { return _examineeInfo; }
            set { _examineeInfo = value; RaisePropertyChanged("ExamineeInfo"); }
        }
        private ImageSource _imageSource;

        public ImageSource ImageSource
        {
            get { return _imageSource; }
            set { _imageSource = value; RaisePropertyChanged("ImageSource"); }
        }

        public RelayCommand ButtonCommand { get; set; }

        public ExamingViewModel()
        {
            ButtonCommand = new RelayCommand(ButtonExec);
            Register<ExamMessage>(this, MessageToken.ShowExamingWindow, (o) =>
            {
                _serialPort = o.SerialPort;
                this.ExamineeInfo = o.ExamineeInfo;
                if (!string.IsNullOrEmpty(ExamineeInfo.photo))
                {
                    ImageSourceConverter converter = new ImageSourceConverter();
                    ImageSource = (ImageSource)converter.ConvertFrom(ExamineeInfo.photoByte);
                }
                else
                {
                    ImageSource = new BitmapImage(new Uri(@"..\Image\nophoto.jpg", UriKind.Relative));
                }
                _canAppend = false;
                _recv = String.Empty;
               Message = "考 试 中";
                ButtonText = "交  卷";
                _serialPort.DataReceived += _serialPort_DataReceived;
            });


        }

        private void ButtonExec()
        {
            if (ButtonText == "交  卷")
            {
                if (MessageBox.Show("确定要交卷吗？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
                    MessageBoxResult.OK)
                {
                    if (string.IsNullOrEmpty(_recv))
                    {
                        MessageBox.Show("请按下控制箱上的【返回】按钮再交卷", "提示");
                        return;
                    }
                    var ffLastIndex = _recv.LastIndexOf("FF", StringComparison.Ordinal) + 2;
                    var fcLastIndex = _recv.LastIndexOf("FA", StringComparison.Ordinal) - 2;
                    var temp = _recv.Substring(ffLastIndex, fcLastIndex - ffLastIndex);
                    if (temp.Length == 24)
                    {
                        Parse(temp);
                        Message = "考试完成";
                        ButtonText = "返  回";
                    }
                }
            }
            else
            {
                
                _serialPort.DataReceived -= _serialPort_DataReceived;
                Send(MessageToken.BackLogin);
            }

        }

        private void Parse(string temp)
        {
            int blowNormal;
            int.TryParse(temp.Substring(0, 2), out blowNormal);
            int pressNormal;
            int.TryParse(temp.Substring(8, 4), out pressNormal);
            int blowScore = (blowNormal / 2) * 2;
            int pressScore = (pressNormal / 30) * 2;
            int score = blowScore + pressScore;
            ScoreText = $"得分：{score}分";
            UploadScore(score);
        }

        private async void UploadScore(int score)
        {
            var jobject = JObject.FromObject(new
            {
                ExamineeInfo.id,
                km = "k4",
                q = ExamineeInfo.code,
                score,
                detail = ""
            });
            await  HttpTool.PostAsJsonAsync("upscore", jobject);

        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = _serialPort.BytesToRead;
            byte[] data = new byte[n];
            _serialPort.Read(data, 0, data.Length);
            string temp = byteToHexStr(data);
            Console.WriteLine(temp);
            if (temp.Contains("FF"))
            {
                _canAppend = true;
            }
            if (_canAppend)
            {
                _recv += temp;
            }
        }
        private string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
    }
}
